package com.automapper.sqlbuilder.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.automapper.constants.ParameterConstants;
import com.automapper.exception.AutoMapperException;
import com.automapper.sqlbuilder.SqlBuilderTemplate;
import com.automapper.utils.ObjectFacade;
import com.automapper.utils.ParameterUtils;
import com.automapper.utils.PropertiesFacade;

public class DeleteSqlBuilder extends SqlBuilderTemplate {	
	
	private static final String VALUE = " #{%s[%s].%s} ";
	
	@Override
	public String buildSql(Object parameterObject, PropertiesFacade propertiesFacade) {  
		AutoMapperException.NullRuntimeException(parameterObject, "Sorry,I refuse to build sql for a null object!"); 
		
		List<String> values = new ArrayList<>();
		Map<String, Object> parameterMap = (Map<String, Object>) parameterObject;
		//获取传入参数
		List<Object> list = ParameterUtils.getParameterList(parameterMap);
		
		String tableName = getTableName(parameterMap);
		ObjectFacade objectFacade = new ObjectFacade(list.get(0));
		String primaryKeyColumn = objectFacade.getPrimaryKeyColumnName();
		String primaryKeyField = objectFacade.getPrimaryKeyField().getFieldName();
		
		StringBuilder tableSql = new StringBuilder();  
	    tableSql.append("delete from ").append(tableName).append(" where ");  
	    tableSql.append(primaryKeyColumn + " in (");
	    for (int i = 0; i  < list.size(); i++) {
	    	values.add(String.format(VALUE, ParameterConstants.PARAM, i, primaryKeyField));
	    }
	    tableSql.append(StringUtils.join(values, ","));  
	    tableSql.append(")");
	    return tableSql.toString();
	}  
}
